package com.train.mgr.config.secrity;


import com.train.common.enums.ResultEnum;
import com.train.common.exception.BusinessException;
import com.train.mgr.config.redis.RedisUtil;
import com.train.mgr.config.secrity.components.TrainAuthenticationToken;
import com.train.mgr.config.secrity.components.UserDetailsServiceImpl;
import com.train.mgr.modules.system.entity.User;
import com.train.mgr.modules.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
*  认证过滤器
*/

@Slf4j
@Component
public class AuthFilter extends OncePerRequestFilter {

    @Resource
    private UserService userService;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Resource
    private RedisUtil redisUtil;

    public AuthFilter(UserService userService,UserDetailsServiceImpl userDetailsService,RedisUtil redisUtil){
        this.userService = userService;
        this.userDetailsService = userDetailsService;
        this.redisUtil = redisUtil;
    }
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 从请求头中获取token字符串并解析
        String token = request.getHeader("Authorization");
       // System.out.println(request.getRequestURI());
        if (token != null) {
            if (redisUtil.exists(token)) {
                Object userId = redisUtil.get(token);
                if (userId == null) {
                    throw new BusinessException(ResultEnum.FORBIDDEN);
                }
                User user = userService.getBaseMapper().selectById(new Long(userId.toString()));
                if (user == null) {
                    throw new BusinessException(ResultEnum.FORBIDDEN);
                }
                UserDetails userDetails = userDetailsService.findPermission(user);
                TrainAuthenticationToken authenticationResult = new TrainAuthenticationToken(userDetails, null ,new Integer(user.getUserType()),user.getOpenId(),user.getId().toString(),token,userDetails ==null ? AuthorityUtils.NO_AUTHORITIES : userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authenticationResult);
            }
        }
        chain.doFilter(request, response);
    }

}
